package permission

import (
	"context"
	"fmt"
	"github.com/samber/lo"
	"private-domain-overseas-service/admin/business/api/internal/repository/permission"
	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"
	"private-domain-overseas-service/pkg/status/bizadmin"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/adminrouter"
	"private-domain-overseas-service/tools/ent/predicate"
	"strings"

	"github.com/zeromicro/go-zero/core/logx"
)

type AdminRouteConstantLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewAdminRouteConstantLogic - 常量路由接口
func NewAdminRouteConstantLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminRouteConstantLogic {
	return &AdminRouteConstantLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// AdminRouteConstant - 常量路由接口
func (l *AdminRouteConstantLogic) AdminRouteConstant() (resp []types.ConstantRoutesResponseItem, err error) {
	adminRouterDao := permission.NewAdminRouterDao(l.ctx, l.svcCtx)

	// 构建条件
	condition := []predicate.AdminRouter{
		// 常量路由
		adminrouter.AdminRouterConstantEQ(bizadmin.Constant),
	}

	// 查询常量路由
	adminRouter, _, err := adminRouterDao.AdminRouterConditionsAll(condition)
	if err != nil {
		return nil, xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("查询常量路由失败: %v", err.Error()))
	}

	// 组装数据
	resp = lo.Map(adminRouter, func(item *ent.AdminRouter, index int) types.ConstantRoutesResponseItem {
		return types.ConstantRoutesResponseItem{
			Name:      item.AdminRouterRouteName,
			Path:      item.AdminRouterRoutePath,
			Component: item.AdminRouterComponent,
			Props:     strings.Contains(item.AdminRouterRoutePath, ":"),
			// 组装meta信息
			Meta: types.RouteMeta{
				Title:      item.AdminRouterMenuName,
				I18nKey:    item.AdminRouterI18nKey,
				Icon:       item.AdminRouterIcon,
				Order:      item.AdminRouterOrder,
				HideInMenu: item.AdminRouterHideInMenu == bizadmin.Hide,
				ActiveMenu: item.AdminRouterActiveMenu,
				MultiTab:   item.AdminRouterMultiTab == bizadmin.MultiTab,
				KeepAlive:  item.AdminRouterKeepAlive == bizadmin.Cache,
				Constant:   item.AdminRouterConstant == bizadmin.Constant,
				Href:       item.AdminRouterHref,
			},
		}
	})
	return resp, nil
}
